package org.strongme.modules.sys.utils;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.strongme.modules.sys.dao.MenuDao;
import org.strongme.modules.sys.dao.RoleDao;
import org.strongme.modules.sys.dao.UserDao;
import org.strongme.modules.sys.entity.Menu;
import org.strongme.modules.sys.entity.Role;
import org.strongme.modules.sys.entity.User;
import org.strongme.modules.sys.security.SystemAuthorizingRealm.Principal;
import org.strongme.modules.sys.service.SystemService;
import org.strongme.util.CacheUtils;
import org.strongme.util.SpringContextHolder;

/**
 * 用户工具类
 * @author Walter
 *
 */
public class UserUtils {

	private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
	private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
	private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private static SystemService systemService = SpringContextHolder.getBean(SystemService.class);
	
	public static final String USER_CACHE = "userCache";
	public static final String USER_CACHE_ID_ = "id_";
	public static final String USER_CACHE_LOGIN_NAME_ = "ln";
	public static final String USER_CACHE_INFO_ = "info";
	public static final String USER_CACHE_LIST_BY_DEPARTMENT_ID_ = "oid_";

	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_ALL_MENU_LIST = "ALLMenuList";
	public static final String CACHE_MENU_LIST = "menuList";
	
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static User get(String id){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		if (user ==  null){
			user = userDao.get(new User(id));
			if (user == null){
				return null;
			}
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getName(), user);
		}
		return user;
	}
	
	/**
	 * 检测驾校和用户手机号是否已经注册
	 * @param mobile
	 * @return
	 */
	public static boolean checkMobile(String mobile) {
		return systemService.checkMobile(mobile);
	}
	public static boolean checkEmail(String email) {
		return systemService.checkUserEmail(email);
	}
	
	public static User getByInfo(String info){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_INFO_ + info);
		if (user == null){
			User tmp = new User();
			tmp.setName(info);tmp.setMobile(info);tmp.setEmail(info);
			user = userDao.getByInfo(tmp);
			if (user == null){
				return null;
			}
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_INFO_ + info, user);
		}
		return user;
	}
	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	public static User getByLoginName(String loginName){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null){
			user = userDao.getByLoginName(new User(null, loginName));
			if (user == null){
				return null;
			}
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getName(), user);
		}
		return user;
	}
	
	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache(){
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		UserUtils.clearCache(getUser());
	}
	
	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearCache(User user){
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_INFO_ + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_INFO_ + user.getName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_INFO_ + user.getMobile());
		CacheUtils.remove(USER_CACHE, USER_CACHE_INFO_ + user.getEmail());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldName());
	}
	
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static User getUser(){
		Principal principal = getPrincipal();
		if (principal!=null){
			User user = get(principal.getId());
			if (user != null){
				return user;
			}
			return new User();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new User();
	}
	
	/**
	 * 获取当前用户角色列表
	 * @return
	 */
	public static List<Role> getRoleList(){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			User user = getUser();
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				Role r = new Role();
				r.setUserId(user.getId());
				roleList = roleDao.findByUserId(r);
			}
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}
	
	
	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(){
		@SuppressWarnings("unchecked")
		List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
		if (menuList == null){
			User user = getUser();
			if (user.isAdmin()){
				menuList = menuDao.findAllList(new Menu());
			}else{
				Menu m = new Menu();
				m.setUserId(user.getId());
				menuList = menuDao.findByUserId(m);
			}
			putCache(CACHE_MENU_LIST, menuList);
		}
		return menuList;
	}
	public static List<Menu> getAllMenuList(){
		@SuppressWarnings("unchecked")
		List<Menu> menuList = (List<Menu>)getCache(CACHE_ALL_MENU_LIST);
		if (menuList == null){
			menuList = menuDao.findAllList(new Menu());
			putCache(CACHE_ALL_MENU_LIST, menuList);
		}
		return menuList;
	}
	
	public static void clearMenuCache(){
		removeCache(CACHE_MENU_LIST);
		removeCache(CACHE_ALL_MENU_LIST);
	}
	
	
	
	
	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
	
	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}
//			subject.logout();
		}catch (UnavailableSecurityManagerException e) {
			
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
	
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
	
	// ============== User Cache ==============
	
		public static Object getCache(String key) {
			return getCache(key, null);
		}
		
		public static Object getCache(String key, Object defaultValue) {
//			Object obj = getCacheMap().get(key);
			Object obj = getSession().getAttribute(key);
			return obj==null?defaultValue:obj;
		}

		public static void putCache(String key, Object value) {
//			getCacheMap().put(key, value);
			getSession().setAttribute(key, value);
		}

		public static void removeCache(String key) {
//			getCacheMap().remove(key);
			getSession().removeAttribute(key);
		}
	
	
}
